﻿using libedi.API;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeBackup.Code
{
    internal class Reback
    {

        public delegate void backmess(string mess);
        public string FileName { get; set; }

        private string FilePath = string.Empty;

        public string lastError = string.Empty;
        WebApi webApi = new WebApi(libedi.SourceType.CODE);
        public string temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempc");
        private backmess Backmess;
        public Reback(string filepath, backmess backmess) {

            this.Backmess = backmess;
            this.FilePath = filepath;
            FileName=Path.GetFileName(filepath);
            if(Directory.Exists(temp))
            {
                Directory.Delete(temp,true);
            }
            Directory.CreateDirectory(temp);
        }

        public bool back()
        {
            List<string> codes = Tools.GetCodeList();
            ZipFile.ExtractToDirectory(FilePath, temp);
            List<string> files= Directory.GetFiles(temp).ToList();
            Backmess("載入文成功！");
            bool repcode = ini.repcode;
            foreach (string file in files)
            {
                
                try
                {
                    string json = File.ReadAllText(file);
                    string dbname = Path.GetFileNameWithoutExtension(file);
                    if (!repcode)
                    {
                        if (codes.Contains(dbname))
                        {
                            Backmess($"代碼{dbname}已存在，跳過");
                            continue;
                        }
                    }
                    Backmess($"回存代碼[{dbname}]");
                    truncate(dbname);
                    DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
              
                    List<string> columns = new List<string>();
                    string tableColumns = string.Empty;
                    foreach (DataColumn dc in dt.Columns)
                    {
                        columns.Add(string.Format("`{0}`", dc.ColumnName));
                    }
                    tableColumns = string.Join(",", columns);

                    Dictionary<int, string> pairs = new Dictionary<int, string>();

                    Parallel.For(0, dt.Rows.Count, index =>
                    {

                        DataRow dr = dt.Rows[index];
                        string Json = JsonConvert.SerializeObject(dr.ItemArray); //"[]"
                        Json = Json.Remove(0, 1);
                        Json = Json.Substring(0, Json.Length - 1);
                        lock (pairs)
                        {
                            pairs.Add(index, string.Format("({0}),", Json));
                        }
                    });

                    Dictionary<int, string> SQlS = pairs.OrderBy(p => p.Key).ToDictionary(p => p.Key, v => v.Value);
                    string formatTableValue = string.Empty;
                    foreach (string item in SQlS.Values)
                    {
                        formatTableValue += item;
                    }
                    formatTableValue = formatTableValue.Substring(0, formatTableValue.Length - 1);
                    string insertSQL = string.Format("insert into `{0}` ({1})  values {2}", dbname, tableColumns, formatTableValue);
                   
                    int count = webApi.Execute(insertSQL);
                    Backmess($"回存數據{count}條");
                }
                catch(Exception ex)
                {
                    Backmess($"error:{ex.Message}");
                    break;
                }

            }
            Backmess($"執行完畢");
            return true;
        }   
    



        /// <summary>
        /// 清空表
        /// </summary>
        private void truncate(string TableName)
        {
           // Backmess("刪除資料！");
            string sql = string.Format("truncate table  `{0}`", TableName);
            int i= webApi.Execute(sql);
           // Backmess("刪除資料成功");
        }
    }
}
